<template>
  <div class="index">
    <!--头部  start-->
    <div class="sreePublic">
      <div id="" style="text-align: center;">
        <em class="iconfont" @click="vfun_back">&#xe61f;</em>
      </div>
      收银台
    </div>
    <!--头部  end-->
    <!--支付方式选择   start-->
    <div class="orderpay">
      <div class="orderpay-many">
        待支付：<span>￥{{Public.formatMoney(orderUnpaidMoney,2)}}</span>
      </div>
      <div class="orderpaytype">
        支付方式
      </div>
      <div class="netsilver">
        <p>普通支付</p>
        <Radio-group v-model="vertical" vertical>
          <Radio label="balance" >
            <em class="iconfont" style="color: #d71618;">&#xe60a;</em>
            <span>余额支付</span>
          </Radio>
          <Radio label="weixin" >
            <em class="iconfont" style="color: #00c901;">&#xe602;</em>
            <span>微信</span>
          </Radio>
          <Radio label="zhifubao">
            <em class="iconfont" style="color: #00a9f2;">&#xe63b;</em>
            <span>支付宝</span>
          </Radio>
        </Radio-group>
      </div>
      <div class="netsilver">
        <p>网银</p>
        <Radio-group v-model="vertical" vertical>
          <Radio label="gongshang" disabled>
            <em class="iconfont" style="color: #d81e06;opacity: 0.6">&#xe614;</em>
            <span style="color: #999999">工商银行</span>
          </Radio>
          <Radio label="jianshe" disabled>
            <em class="iconfont" style="color: #003b8f;opacity: 0.6">&#xe668;</em>
            <span style="color: #999999">建设银行</span>
          </Radio>
          <Radio label="nongye" disabled>
            <em class="iconfont" style="color: #008666;opacity: 0.6">&#xe693;</em>
            <span style="color: #999999">农业银行</span>
          </Radio>
          <Radio label="zhaoshang" disabled>
            <em class="iconfont" style="color: #e50012;opacity: 0.6">&#xe619;</em>
            <span style="color: #999999">招商银行</span>
          </Radio>
        </Radio-group>
      </div>
    </div>
    <!--支付方式选择   end-->
    <!--底部  start-->
    <div class="footer" @click="vfun_button">
      确认支付
    </div>
    <!--底部  end-->
    <!--输入支付密码弹窗框  start-->
    <mt-popup v-model="popupVisible" position="bottom">
      <div class="psss-word">
        <div class="box">
          <div class="box-th">请输入支付密码</div>
          <div class="box-input">
            <label>
              <input ref="passInput" type="text" v-model="operatorPayPassword" maxlength="6"/>
            </label>
            <input class="txet-inout" type="password" v-model="operatorPayPassword[0]" maxlength="1">
            <input class="txet-inout" type="password" v-model="operatorPayPassword[1]" maxlength="1">
            <input class="txet-inout" type="password" v-model="operatorPayPassword[2]" maxlength="1">
            <input class="txet-inout" type="password" v-model="operatorPayPassword[3]" maxlength="1">
            <input class="txet-inout" type="password" v-model="operatorPayPassword[4]" maxlength="1">
            <input class="txet-inout" type="password" v-model="operatorPayPassword[5]" maxlength="1">
          </div>
          <div class="pay-ok">
            <a @click="popupVisible=false">取消</a>
            <a @click="payment">付款</a>
          </div>
        </div>
      </div>
    </mt-popup>
    <!--输入支付密码弹窗框  end-->
    <wei-xin v-show="weiXinBillShow" @closeShowBtn = "closeShowBtn"></wei-xin>
  </div>
</template>

<script>
  import weiXin from  '../../components/payDigLog/weixinPayBill'
  import { Toast } from 'mint-ui';  //引入弹框
  import { MessageBox } from 'mint-ui';
  export default {
    components: {
      weiXin
    },
    name: 'index',
    data () {
		return {
      weiXinBillShow:false,    //微信支付单
			operatorPayPassword:[],    //输入的密码值
			popupVisible:false,      //支付密码弹出框（显示）或（不显示）
			vertical: 'balance',   //选择的支付方式（默认余额支付）
			orderUnpaidMoney:'1',    //待支付金额
			vue_urlNow: window.location.href,
		}
    },
    methods:{

      //关闭微信支付弹出框
      closeShowBtn(){
        this.weiXinBillShow = false;
      },

		  //（确认支付）按钮
		vfun_button(){
			if(this.vertical =="weixin"){
				this.weixinPayment();
			} else if(this.vertical == "zhifubao"){
				this.alipayPayment();
			}else{
				this.axios({
					method: 'PATCH',
					url: "/v3/member/operators/payPasswordExited",
					data:{}
				}).then((res) => {
					if(res.data.exited == true){
					  this.popupVisible=true;
					}else{
					  this.$router.push({path:"/payPassword"});
					}
				}).catch((err)=>{

				});
			}
		},

		  //支付密码输入后，点击（付款按钮）
		payment(){
			this.axios({
			  method: 'PATCH',
			  url: "/v3/sale/orders/"+localStorage.getItem("orderCode")+"/"+this.md5(this.operatorPayPassword).toUpperCase()+"/paymentByApp",
			  data:{
			  }
			}).then((res) => {
        this.operatorPayPassword = [];
			  Toast({
				message: '支付成功',
				iconClass: 'fontSize iconfont icon-chenggong'
			  });
			  this.$router.push({path:'/orderList'})
			}).catch((err)=>{
        this.operatorPayPassword = [];
			  Toast({
				message: err.response.data,
				iconClass: 'fontSize iconfont icon-shibai'
			  });
			});
		},

		  //初始化页面待支付金额
		orderPay(){
			this.axios({
			  method: 'GET',
			  url: "/v3/sale/orders/"+localStorage.getItem("orderCode"),
			  data:{}
			}).then((res) => {
			  this.orderUnpaidMoney=res.data.orderUnpaidMoney;
			}).catch((err)=>{
			});
		},

		  //离开收银台，返回上个页面
		vfun_back(){
			MessageBox({
			  title: '确认要离开收银台？',
			  message: '您的订单尚未完成支付，请尽快完成支付！',
			  confirmButtonText:'确认离开',
			  cancelButtonText:'继续支付',
			  confirmButtonClass:'redBg',
			  showCancelButton: true
			}).then(btnType=>{
			  if(btnType=='confirm'){
				this.$router.push({path:'/orderList'})
			  }
			})
		},

		  //支付宝支付方式
		alipayPayment(){
			var orderCode = localStorage.getItem("orderCode");
			if(orderCode != undefined && orderCode != ""){
			  this.axios({
				method: "GET",
				url: "/v3/sale/orders/" + orderCode
			  }).then((res) => {
				var list = res.data.saleOrderGoodsDataList;
				var subject = "";
				var productCode = "";
				var body = "";
				var totalAmout = res.data.orderUnpaidMoney; //待支付金额
				if(list != null && list.length > 0){
				  for(var i=0;i<list.length;i++){
					var orderGood = list[i];
					subject += orderGood.goodsName+",";
					productCode+=orderGood.goodsCode+",";
					body += (orderGood.goodsRemark != null && orderGood.goodsRemark != "") ? orderGood.goodsRemark+"," : "";
				  }
				  this.axios({
					method: 'POST',
					url: "/v3/alipay/pays/appWebAlipayPay",
					params:{
					  "outTradeNo" : orderCode,
					  "totalAmout" : totalAmout,
					  "subject" : subject.substring(0,subject.length-1),
					  "productCode" : productCode.substring(0,productCode.length-1),
					  "body" : ((body != "") ? body.substring(0,body.length-1) : body),
					  "timeoutExpress" : "3m",
					}
				  }).then((res) => {
					console.log(res.data);
					const div = document.createElement('div');
					div.innerHTML = res.data;
					document.body.appendChild(div);
					document.forms.punchout_form.submit();
				  }).catch((err)=>{
					Toast({
					  message: err.response.data,
					  iconClass: 'fontSize iconfont icon-shibai'
					});
				  });
				}
			  });
			}
		},

		  //微信支付方式
		weixinPayment() {
			var vm = this;
			var orderCode = localStorage.getItem("orderCode");
			if (typeof WeixinJSBridge != "undefined"){//微信浏览器内置对象。参考微信官方文档
				this.axios({
					method: 'GET',
					url: "/v3/weixin/pays/makeWeixinCodeRequestUrl",
					params: {
						"orderCode": orderCode
					}
				}).then((res) => {
					//直接访问服务端返回的获取code的请求URL
					console.log("Request Url: " + res.data);
					window.location.href = res.data;
				}).catch((err) => {
					Toast({
						message: err.response.data,
						iconClass: 'fontSize iconfont icon-shibai'
					});
				});
			} else {
				this.axios({
					method: "GET",
					url: "/v3/sale/orders/" + orderCode
				}).then((res) => {
					var list = res.data.saleOrderGoodsDataList;
					var subject = "";
					var body = "";
					var totalAmout = res.data.orderUnpaidMoney; //待支付金额
					if(list != null && list.length > 0) {
						for(var i = 0; i < list.length; i++) {
							var orderGood = list[i];
							subject += orderGood.goodsName + ",";
							body += (orderGood.goodsRemark != null && orderGood.goodsRemark != "") ? orderGood.goodsRemark + "," : "";
						}
						vm.axios({
							method: 'POST',
							url: "/v3/weixin/pays/payment",
							params: {
								"outTradeNo": orderCode,
								"totalFee": totalAmout,
								"body": subject.substring(0, subject.length - 1),
								"detail": ((body != "") ? body.substring(0, body.length - 1) : body),
								"tradeType": "MWEB",  //手机网页支付
								"weixinCode": ""
							}
						}).then((res) => {
							window.location.href = res.data;
							setTimeout('this.weiXinBillShow = true', 1000); //跳转中间页面
						}).catch((err) => {
							Toast({
								message: err.response.data,
								iconClass: 'fontSize iconfont icon-shibai'
							});
						});
					}
				});
			}
		},
    },
    mounted() {
		var vm = this;
		this.orderPay();
		if(this.vue_urlNow.indexOf("?code=") != -1) { //如果是微信登录，则链接中包含"?code="
			//如果是微信登录，则链接中包含"?code="
			var firstQue = this.vue_urlNow.indexOf("?");
			var rootUrl = this.vue_urlNow.substr(0, firstQue);
			this.vue_urlNow = this.vue_urlNow.substr(firstQue + 1); //取得所有参数   stringvar.substr(start [, length ]
			var secondQue = this.vue_urlNow.indexOf("?");
			var orderCodeAndJsessionId = this.vue_urlNow.substr(secondQue + 11); //过滤掉?cmemberCode=
			var thirdSplit = orderCodeAndJsessionId.indexOf("&");
			var orderCode = orderCodeAndJsessionId.substr(0, thirdSplit); //过滤掉?cmemberCode=
			var jsessionId = orderCodeAndJsessionId.substr(thirdSplit + 12);

			var arr = this.vue_urlNow.split("&"); //各个参数放到数组里
			var par = arr[0];
			var weixinCode = par.substring(par.indexOf("=") + 1, par.length);
			this.axios({
				method: "GET",
				url: "/v3/sale/orders/" + orderCode
			}).then((res) => {
				var list = res.data.saleOrderGoodsDataList;
				var subject = "";
				var body = "";
				var totalAmout = res.data.orderUnpaidMoney; //待支付金额
				if(list != null && list.length > 0) {
					for(var i = 0; i < list.length; i++) {
						var orderGood = list[i];
						subject += orderGood.goodsName + ",";
						body += (orderGood.goodsRemark != null && orderGood.goodsRemark != "") ? orderGood.goodsRemark + "," : "";
					}
					vm.axios({
						method: 'POST',
						url: "/v3/weixin/pays/payment",
						params: {
							"outTradeNo": orderCode,
							"totalFee": totalAmout,
							"body": subject.substring(0, subject.length - 1),
							"detail": ((body != "") ? body.substring(0, body.length - 1) : body),
							"tradeType": "JSAPI",  //公众号支付
							"weixinCode": weixinCode,
							"jsessionId": jsessionId
						},
					}).then((res) => {
						WeixinJSBridge.invoke(
							'getBrandWCPayRequest',{
								"appId":res.data.appId,     //公众号名称，由商户传入
								"timeStamp":res.data.timeStamp, //时间戳，自1970年以来的秒数
								"nonceStr":res.data.nonceStr, //随机串
								"package":res.data.packageExt,
								"signType":res.data.signType, //微信签名方式：
								"paySign":res.data.paySign //微信签名
							},
							function(res){
								// 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
								if(res.err_msg == "get_brand_wcpay_request:ok" ){
									Toast({
										message: '支付成功',
										iconClass: 'fontSize iconfont icon-chenggong'
									});
									window.location.hash = '#/orderList';
								}else{
									Toast({
										message: "支付失败, 请联系客服",
										iconClass: 'fontSize iconfont icon-shibai'
									});
								}
							}
						);
					}).catch((err) => {
						Toast({
							message: err.response.data,
							iconClass: 'fontSize iconfont icon-shibai'
						});
					});
				}
			});
		}
	}
  }</script>


<style scoped>
  *{
    transition: 0.2s;
  }
  h1, h2 {
    font-weight: normal;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }
  .index{
    box-sizing: border-box;
    background: #d2d3d9;
  }

  .orderpay{
    background: #fff;
    margin-top: 1.2rem;
  }

  .footer{
    position: fixed;
    bottom: 0.5%;
    width: 98%;
    left: 1%;
    text-align: center;
    color: #fff;
    height: 1.4rem;
    font-size: 16px;
    background: #D50B0A;
    line-height: 1.4rem;
    border-radius:4px ;
  }
  .orderpay-many{
    text-align: right;
    padding: 0.4rem 0.1rem;
    border-bottom: 1px solid #bbb;
  }
  .orderpay-many span{
    color: #D50B0A;
  }
  .orderpaytype{
    background: #C0C1C4;
    padding: 0.25rem 0.4rem;
  }
  .netsilver{
    border-bottom: 1px solid #bbb;
    padding: 0rem 0;
    padding-bottom: 0.4rem;
  }
  .netsilver p{
    padding: 0.2rem 0.5rem;
    border-bottom: 1px solid #bbb;
  }
  .netsilver div{
    padding: 0rem 0.7rem;
  }
  .netsilver label{
    padding: 0.1rem 0;
    font-size: 16px;
    height: auto!important;
  }
  .netsilver em{
    font-size: 26px;
    position: relative;
    top: 5px;
    margin-left: 0.2rem;
    margin-right: 0.2rem;
  }
  .psss-word{
    width: 10rem;
    padding: 0.7rem 0;
    background: rgba(0,0,0,0)!important;

  }
  .box{
    text-align: center;
    border-radius:2px ;
    width: 8rem;
    margin: 0 auto;
    border: 1px solid #e0e0e0;
  }
  .box-input{
    margin:0.3rem auto;
    width:calc(7.2rem + 3px) ;
    overflow: hidden;
    height: 1.2rem;
    border: 1.2px solid #e0e0e0;
    position: relative;
  }
  .box-input .txet-inout{
    width: 1.2rem;
    height: 1.2rem;
    border-right: 1px solid #e0e0e0;
    border-top:0;
    border-left:0 ;
    border-bottom: 0;
    text-align: center;
    display: block;
    float: left;
    position: relative;
    z-index: 100;
    line-height: 1.2rem;
  }
  .box-input .txet-inout:last-child{
    border-right: 0 ;
  }
  .box-input label{
    position: absolute;
    width: 7rem;
    height: 1.2rem;
    z-index: 300;
    top: 0;
    left:0;
  }
  .box-input label input{

    position: absolute;
    left: -100rem;
  }
  .box-th{
    height: 1rem;
    line-height: 1rem;
    border-bottom: 1px solid #e0e0e0;
    font-size: 18px;
  }
  .pay-ok{
    border-top:1px solid #e0e0e0 ;
    overflow: hidden;
    padding: 0.3rem 0;
  }
  .pay-ok a{
    display: block;
    width: 3.5rem;
    height: 1rem;
    text-align: center;
    line-height: 1rem;
    border-radius:2px ;
  }
  .pay-ok a:first-child{
    float: left;
    border: 1px solid #e0e0e0;
    box-sizing: border-box;
    margin-left: 0.3rem;
  }
  .pay-ok a:last-child{
    float: right;
    color: #fff;
    background-color: #D50B0A;
    margin-right: 0.3rem;
  }
</style>
